import socket
import threading
import select
import signal
import sqlite3 as sql
import os    
import re
def listToStr(lst):
    if(lst.__len__()==0):
        return '-'
    ret = ""
    first = 0
    for i in lst:
        for j in i:
            if(j==None):
                ret = ret + ', ,'
            else:
                if first == 0:
                    ret = ret+j
                    first = 1
                else:
                    ret = ret + ',' + j
        first = 0
        ret = ret+'/'
    return ret.__str__()

class threadedRun(threading.Thread):
 
    def __init__(self, channel):
        threading.Thread.__init__(self)
        self.channel = channel
    
    def run(self):
        channel = self.channel
        while True:
            home = os.path.expanduser('~')
            dbconnection = sql.connect(home+"\\testdb")
            cu = dbconnection.cursor()
            recieved = channel.recv(100)
            print recieved
            if recieved[0:3]=="use":
                print 'adding user'               
                vals = re.split(' ',recieved[4:])
                cu.execute('''select * from users where username='%s' ''' %vals[0])
                a=cu.fetchall()
                if(a.__len__()==0):
                    cu.execute('''insert into users values('%s','%s','%s')''' %(vals[0],vals[1],vals[2]))
                    print "Sucessfuly added user %s" %vals[0]
                    channel.send('1')
                    dbconnection.commit()
                else:
                    channel.send('0')
            elif recieved[0:4]=="auth":
                print 'checking login'
                vals = re.split(' ', recieved[5:])
                cu.execute('''select * from users where username = '%s' and password = '%s' ''' %(vals[0],vals[1]))
                a=cu.fetchall()
                if(a.__len__() > 0):
                    channel.send('1')
                else:
                    channel.send('0')
            elif recieved[0:3]=='gus':
                print 'sending user list'
                cu.execute('''select * from users''')
                a=cu.fetchall()
                channel.send(listToStr(a))
            elif recieved[0:3]=='gev':
                print 'sending event list'
                cu.execute('''select * from events''')
                a=cu.fetchall()
                channel.send(listToStr(a))
            elif recieved[0:3]=='ade':
                print 'handling addition or deletion of an event'
                cu.execute('''select * from eventlist where user = '%s' and event = '%s' ''')
                a = cu.fetchall()
                if(a.__len__() > 0):
                    cu.execute('''delete from eventList values('%s','%s')''' %(vals[0],vals[1]))
                else:
                    cu.execute('''insert into eventList values('%s','%s')''' %(vals[0],vals[1]))
            else:
                print 'Connection terminated'
                channel.close()
                break
        threading.Thread.__reduce__(self)



mySocket = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
mySocket.bind(('', 12345))
mySocket.listen(5)

##otherSockets = [mySocket]
##while True:
##    (sread, swrite, sexc) = select.select(otherSockets, [], [])
##    for sock in sread:
##        if sock==mySocket:
##            otherSockets.append(accept_new_connection(mySocket))
##        else:
##            strin = sock.recv(100)
##        if strin =='quit':
##            sock.close()
##            otherSockets.remove(sock)
##        else:
##            host, port = sock.getpeername()
##            sock.send(strin)
##def accept_new_connection(socket):
##    newsock, (remhost, remport) = socket.accept()
##    print remhost, remport
socketlist = [mySocket]
while True:
    channel, details = mySocket.accept()
    print 'Connection opened with', details
    t = threadedRun(channel)
    t.start()
##    recieved = channel.recv(100)
##    print recieved
##    while recieved != "quit":
##        channel.send(recieved)
##        recieved = channel.recv(100)
##        print recieved
##    print 'Connection terminated with', details
##    channel.close()


